<template>
    <div>
        <!-- 面包屑导肮 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片 -->
        <el-card class="box-card">
            <div class="search">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-input v-model="queryInfo.query" placeholder="请输入内容" class="input-with-select">
                            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                        </el-input>
                    </el-col>
                    <el-col :span="6">
                        <el-button type="primary" @click="showAddDialog">添加用户</el-button>
                    </el-col>
                </el-row>
            </div>
            <el-table style="width: 100%" :data="userList" stripe border>
                <el-table-column type="index" />
                <el-table-column label="姓名" prop="username" width="180" />
                <el-table-column label="邮箱" prop="email" width="180" />
                <el-table-column label="电话" prop="mobile" />
                <el-table-column label="角色" prop="role_name" />
                <el-table-column label="状态">
                    <!-- v-slot：可以缩写为# 2.6新语法 -->
                    <template #default="scope">
                        <el-switch v-model="scope.row.mg_state" @change="updateUserState(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template #default="scope">
                        <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable="false">
                            <el-button type="primary" icon="el-icon-edit" size="small"
                                @click="showUpdateDialog(scope.row.id)">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="small"
                                @click="showUpdateRole(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
                            <el-button type="danger" icon="el-icon-delete" size="small"
                                @click="openDeleteBox(scope.row.id)">
                            </el-button>
                        </el-tooltip>
                    </template>

                </el-table-column>

            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum" :page-sizes="[2,5, 10, 15]" :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加修改对话框 -->
        <el-dialog :title="this.addUpdateFormOper === 'add'?'添加用户':'修改用户'" :visible.sync="isShowDialog" width="30%">
            <span>
                <!-- 添加用户表单 -->
                <el-form label-width="65px" class="add_form" :model="addUpdateForm" :rules="addRules"
                    ref="addUpdateForm">
                    <!-- 用户名 -->
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="addUpdateForm.username" :disabled="addUpdateFormOper!=='add'"></el-input>
                    </el-form-item>
                    <!-- 密码 -->
                    <el-form-item label="密码" prop="password" v-if="addUpdateFormOper==='add'">
                        <el-input v-model="addUpdateForm.password"></el-input>
                    </el-form-item>
                    <!-- 邮箱 -->
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="addUpdateForm.email"></el-input>
                    </el-form-item>
                    <!-- 手机 -->
                    <el-form-item label="手机" prop="mobile">
                        <el-input v-model="addUpdateForm.mobile"></el-input>
                    </el-form-item>

                </el-form>
            </span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogCancle">取 消</el-button>
                <el-button type="primary" @click="dialogOK">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配角色对话框 -->
        <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRightDialogClose">
            <span>
                <p>当前用户：{{userInfo.username}}</p>
                <p>当前角色：{{userInfo.role_name}}</p>
                <p>分配新角色
                    <el-select v-model="selectRoleId" placeholder="请选择">
                        <el-option v-for="role in roleList" :key="role.id" :label="role.roleName" :value="role.id">
                        </el-option>
                    </el-select>
                </p>
            </span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateRole">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    reqUserList,
    reqUpdateUserState,
    reqUserById,
    reqAddUser,
    reqUpdateUser,
    reqDeleteUserById,
    reqRolesList,
    reqSetUserRole
} from '@/api'
export default {
    created() {
        //发送请求拿到用户列表
        this.getUserList()
    },

    data() {
        return {
            userList: [],
            queryInfo: {
                query: '',
                pagenum: 1,
                pagesize: 2
            },
            total: 0,
            isShowDialog: false,
            addUpdateForm: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
            addRules: {
                username: [
                    {
                        required: true,
                        message: '请输入用户名',
                        trigger: 'blur'
                    },
                    {
                        min: 4,
                        max: 10,
                        message: '长度在 4 到 10 个字符',
                        trigger: 'blur'
                    }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    {
                        min: 6,
                        max: 15,
                        message: '密码长度6-15位',
                        trigger: 'blur'
                    }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {
                        pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
                        message: '请输入正确邮箱地址',
                        trigger: 'blur'
                    }
                ],
                mobile: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    {
                        pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                        message: '请输入正确手机号',
                        trigger: 'blur'
                    }
                ]
            },

            addUpdateFormOper: 'add',
            setRoleDialogVisible: false,
            userInfo: {},
            roleList: [],
            selectRoleId: ''
        }
    },
    methods: {
        //pagesize改变调用
        handleSizeChange(val) {
            this.queryInfo.pagesize = val
            this.getUserList()
        },
        handleCurrentChange(val) {
            this.queryInfo.pagenum = val
            this.getUserList()
        },
        async getUserList() {
            const {
                data,
                meta: { msg, status }
            } = await reqUserList(this.queryInfo)
            if (200 !== status) return this.message.error(msg)
            this.userList = data.users
            this.total = data.total
        },
        async updateUserState(userInfo) {
            console.log(userInfo)

            const {
                data,
                meta: { msg, status }
            } = await reqUpdateUserState({ id: userInfo.id, state: userInfo.mg_state })
            if (200 !== status) {
                userInfo.mg_state = !userInfo.mg_state
                return this.$message.error(msg)
            }
            this.$message.success(msg)
            this.getUserList()
        },
        showAddDialog() {
            this.isShowDialog = true
            //打开后重新渲染dom 再选然后执行清空就不会报错了
            this.$nextTick(() => {
                this.$refs.addUpdateForm.resetFields()
            })
            this.addUpdateFormOper = 'add'
        },
        showUpdateDialog(id) {
            this.isShowDialog = true
            this.addUpdateFormOper = 'edit'
            this.getUserById(id)
        },
        async getUserById(id) {
            const {
                data,
                meta: { msg, status }
            } = await reqUserById(id)
            if (200 !== status) return this.$message.error(msg)
            this.addUpdateForm = data
        },
        dialogCancle() {
            this.isShowDialog = false
            if (this.addUpdateFormOper !== 'add') return
            this.$refs.addUpdateForm.resetFields()
        },
        dialogOK() {
            this.$refs.addUpdateForm.validate(async (valid) => {
                // 验证有误
                if (!valid) return

                if (this.addUpdateFormOper === 'add') {
                    // 发送添加用户请求
                    const {
                        data,
                        meta: { msg, status }
                    } = await reqAddUser(this.addUpdateForm)
                    if (201 !== status) return this.$message.error(msg)
                    this.$message.success(msg)
                    this.getUserList()
                    this.isShowDialog = false
                } else {
                    //发送修改用户请求
                    const { id, email, mobile } = this.addUpdateForm
                    const {
                        data,
                        meta: { msg, status }
                    } = await reqUpdateUser({ id, email, mobile })
                    if (200 !== status) return this.$message.error(msg)
                    this.$message.success(msg)
                    this.getUserList()
                    this.isShowDialog = false
                }
            })
        },
        async deleteUser(id) {
            const {
                data,
                meta: { msg, status }
            } = await reqDeleteUserById(id)
            if (200 !== status) return this.$message.error(msg)
            this.$message.success(msg)
            this.queryInfo.pagenum = 1
            this.getUserList()
        },
        openDeleteBox(id) {
            this.$confirm('是否删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    this.deleteUser(id)
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
        },
        async showUpdateRole(userInfo) {
            this.userInfo = userInfo
            const {
                data,
                meta: { msg, status }
            } = await reqRolesList()
            if (200 !== status) return this.$message.error(msg)
            this.roleList = data
            this.setRoleDialogVisible = true
        },

        setRightDialogClose() {
            this.selectRoleId = ''
        },
        async updateRole() {
            const {
                data,
                meta: { msg, status }
            } = await reqSetUserRole(this.userInfo.id, this.selectRoleId)
            if (200 !== status) return this.$message.error(msg)
            this.$message.success(msg)
            this.getUserList()
            this.setRoleDialogVisible = false
        }
    }
}
</script>
<style lang="less" scoped>
</style>